import router from "@/router";
import { useUserStore } from "@/stores/user";
import axios, { type Method } from "axios";
import { ElMessage } from "element-plus";

const service = axios.create({
  baseURL: "https://api-hmzs.itheima.net/tj",
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 获取用户信息
    const {token} = useUserStore();
    if(token){
      config.headers.Authorization = `Bearer ${token}`
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        // 认证失败，可以在这里处理重新登录的逻辑
        const store = useUserStore();
        store.removeToken();
        // 跳转登录页
        router.push("/login");
        ElMessage.error("认证失败，请重新登录");
      } else if (error.response.status === 400) {
        // 参数错误，后端有提示信息
        ElMessage.error(error.response.data.msg);
      } else {
        // 未知错误，如果后端有提示信息就显示，否则显示未知错误
        ElMessage.error(error.response.data?.msg || "未知网络错误");
      }
    } else {
      if (error.message.includes("timeout")) {
        ElMessage.error("网络请求超时");
      } else {
        ElMessage.error("请检查网络状态");
      }
    }
    return Promise.reject(error);
  }
);

// 后端返回值类型
export interface ServiceResponse<T> {
  code: number;
  msg: string;
  data: T;
}
export const request = <T = unknown>(
  url: string,
  method: Method = "get",
  submitData?: Object
) => {
  return service.request<T, ServiceResponse<T>>({
    url,
    method,
    [method.toUpperCase() === "GET" ? "params" : "data"]: submitData,
  });
};

export default service;
